//
//  ZCPutInStoragePlanDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/29.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCPutInStoragePlanDetailViewController.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCPutInStoragePlanModel.h"
#import "ZCAbnormalSignViewController.h"
#import "ZCAbnormalMissingTableViewCell.h"
#import "ZCAssignCodeEditVinViewController.h"

static NSString *detailCellID = @"ZCTaskTotalNumTableViewCell";
static NSString *locationCellID = @"ZCAbnormalMissingTableViewCell";

@interface ZCPutInStoragePlanDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *handleView;
@property (nonatomic, strong) UIButton *exceptionButton;
@property (nonatomic, strong) UIButton *putInStorageButton;

@property (nonatomic, strong) ZCStoragePlanInfoModel *detailModel;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCPutInStoragePlanDetailViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(90 * 11) + 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = ZCColor(0xf7f8fb, 1);
        _tableView.scrollEnabled = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:detailCellID];
        [_tableView registerClass:[ZCAbnormalMissingTableViewCell class] forCellReuseIdentifier:locationCellID];
    }
    return _tableView;
}

- (UIView *)handleView {
    if (!_handleView) {
        _handleView = [[UIView alloc] init];
        _handleView.backgroundColor = [UIColor whiteColor];
        _handleView.hidden = YES;
    }
    return _handleView;
}

- (UIButton *)exceptionButton {
    if (!_exceptionButton) {
        _exceptionButton = [[UIButton alloc] init];
        [_exceptionButton setTitle:@"异常登记" forState:UIControlStateNormal];
        [_exceptionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_exceptionButton setBackgroundColor:ZCColor(0xff6113, 1)];
        _exceptionButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(28)];
        _exceptionButton.layer.masksToBounds = YES;
        _exceptionButton.layer.cornerRadius = space(6);
        [_exceptionButton addTarget:self action:@selector(exceptionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _exceptionButton;
}

- (UIButton *)putInStorageButton {
    if (!_putInStorageButton) {
        _putInStorageButton = [[UIButton alloc] init];
        [_putInStorageButton setTitle:@"入库确认" forState:UIControlStateNormal];
        [_putInStorageButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_putInStorageButton setBackgroundColor:ZCColor(0xff6113, 1)];
        _putInStorageButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(28)];
        _putInStorageButton.layer.masksToBounds = YES;
        _putInStorageButton.layer.cornerRadius = space(6);
        [_putInStorageButton addTarget:self action:@selector(putInStorageButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _putInStorageButton.timeInterval = 3;
    }
    return _putInStorageButton;
}

- (void)setFromPlan:(BOOL)fromPlan {
    _fromPlan = fromPlan;
    self.handleView.hidden = fromPlan;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"分配入库";
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, space(30), space(30))];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonToBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.handleView];
    [self.handleView addSubview:self.exceptionButton];
    [self.handleView addSubview:self.putInStorageButton];
    [self updateViewConstraints];
    self.type = self.isClick ? @"CLICK" : @"SCAN";
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    NSLog(@"测试一下------哈哈");
    //文件修改不管用啦？
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)leftButtonToBack {
    //实车位置功能必须进行时，放开注释
    
//    if (self.detailModel.storeDetail.length > 0 || self.fromPlan) {
        [self.navigationController popViewControllerAnimated:YES];
//    }else {
//        [self.hud showAnimated:YES];
//        self.hud.mode = MBProgressHUDModeText;
//        self.hud.label.text = @"请绑定实车位置";
//        [self.hud hideAnimated:YES afterDelay:HudTime];
//    }
    
}

- (void)exceptionButtonClick:(UIButton *)sender {
    ZCAbnormalSignViewController *signVC = [[ZCAbnormalSignViewController alloc] init];
    signVC.releaseId = self.detailModel.Id;
    signVC.taskType = @"42";
    signVC.visitType = @"CLICK";
    signVC.orderNoAlloc = self.detailModel.ownerOrderNo;
    signVC.vinAlloc = self.detailModel.lotNo1;
    signVC.vehicleAlloc = self.detailModel.materielId;
    signVC.storageAlloc = self.detailModel.storeHouseName;
    signVC.isCanSend = self.detailModel.isCanSend;
    [self.navigationController pushViewController:signVC animated:YES];
}

- (void)putInStorageButtonClick:(UIButton *)sender {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.detailModel.storeHouseId forKey:@"houseId"];
    [param setObject:self.detailModel.Id forKey:@"key"];
    
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:PutInStorageCommit params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.detailModel = [ZCStoragePlanInfoModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
                if (!weakSelf.fromPlan) {
                    weakSelf.handleView.hidden = [weakSelf.detailModel.status integerValue] == 10 ? NO : YES;
                }
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}


#pragma mark - 网络请求

- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.houseId forKey:@"houseId"];
    [param setObject:self.key forKey:@"key"];
    [param setObject:self.type forKey:@"visitType"];
    
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:PutInStoragePlanDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.detailModel = [ZCStoragePlanInfoModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
                if (!weakSelf.fromPlan) {
                    weakSelf.handleView.hidden = [weakSelf.detailModel.status integerValue] == 10 ? NO : YES;
                }else {
                    if ([weakSelf.detailModel.status integerValue] == 10) {
                        weakSelf.tableView.frame = CGRectMake(0, 0, SCREENWIDTH, space(90 * 9) + 64);
                    }
                }
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 11;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 10) {
        ZCAbnormalMissingTableViewCell *missCell = [tableView dequeueReusableCellWithIdentifier:locationCellID forIndexPath:indexPath];
        missCell.selectionStyle = UITableViewCellSelectionStyleNone;
        missCell.title = @"实车确认";
        missCell.titleColor = ZCColor(0x000000, 0.87);
        missCell.content = self.detailModel.storeDetail;
        missCell.contentColor = ZCColor(0xff8213, 1);
        missCell.canSelected = (self.detailModel.storeDetail.length > 0 || self.fromPlan) ? NO : YES;
        return missCell;
    }else {
        ZCTaskTotalNumTableViewCell *numCell = [tableView dequeueReusableCellWithIdentifier:detailCellID forIndexPath:indexPath];
        numCell.selectionStyle = UITableViewCellSelectionStyleNone;
        numCell.line = YES;
        if (indexPath.row == 0) {
            numCell.title = @"通知单号";
            numCell.content = self.detailModel.noticeNo;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 1) {
            numCell.title = @"订单号";
            numCell.content = self.detailModel.ownerOrderNo;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 2) {
            numCell.title = @"车架号";
            numCell.content = self.detailModel.lotNo1;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 3) {
            numCell.title = @"客户";
            numCell.content = self.detailModel.ownerName;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 4) {
            numCell.title = @"预计入库时间";
            numCell.content = self.detailModel.recvDate;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 5) {
            numCell.title = @"收货仓库";
            numCell.content = self.detailModel.storeHouseName;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 6) {
            numCell.title = @"承运商";
            numCell.content = self.detailModel.carrierName;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 7) {
            numCell.title = @"车牌号";
            numCell.content = self.detailModel.plateNumber;
            numCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 8) {
            numCell.title = @"状态";
            numCell.content = [self.detailModel.status integerValue] == 10 ? @"未入库" : @"已入库";
            numCell.contentColor = ZCColor(0xff8213, 1);
        }else if (indexPath.row == 9) {
            numCell.title = @"库位号";
            numCell.content = self.detailModel.locationNo;
            numCell.contentColor = ZCColor(0xff8213, 1);
        }
        return numCell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.row == 10 && !self.fromPlan && self.detailModel.storeDetail.length == 0) {
        ZCAssignCodeEditVinViewController *editVC = [[ZCAssignCodeEditVinViewController alloc] init];
        editVC.key = self.detailModel.lotNo1;
        editVC.name = @"location";
        [self.navigationController pushViewController:editVC animated:YES];
    }
}

- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    [_handleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.top.equalTo(weakSelf.tableView.mas_bottom);
    }];
    
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    [attr setObject:[UIFont systemFontOfSize:FontSize(28)] forKey:NSFontAttributeName];
    CGSize size = [_exceptionButton.titleLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, space(90)) options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    [_exceptionButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(weakSelf.handleView.mas_top).offset(space(80));
        make.centerY.equalTo(weakSelf.handleView.mas_centerY);
        make.left.equalTo(weakSelf.handleView.mas_left).offset(space(80));
        make.right.equalTo(weakSelf.handleView.mas_centerX).offset(-space(40));
        make.height.mas_equalTo(size.height + space(40));
    }];
    
    [_putInStorageButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(weakSelf.exceptionButton.mas_top);
        make.centerY.equalTo(weakSelf.exceptionButton.mas_centerY);
        make.left.equalTo(weakSelf.handleView.mas_centerX).offset(space(40));
        make.right.equalTo(weakSelf.handleView.mas_right).offset(-space(80));
        make.height.equalTo(weakSelf.exceptionButton.mas_height);
    }];
}


@end
